import Vue from 'vue'
import VueRouter from 'vue-router'
// 主页
import Home from '@/views/Home.vue'
// 登录页面
import Login from '@/views/Login.vue'
// 欢迎页面
import Welcome from '@/views/Welcome.vue'
// 商品----分类
import Cate from '@/views/goods/Cate.vue'
// 商品----列表
import List from '@/views/goods/List.vue'
// 订单
import Order from '@/views/order/Order.vue'
// 权限----权限列表
import Rights from '@/views/power/Rights.vue'
// 权限----角色列表
import Roles from '@/views/power/Roles.vue'
// 数据报表
import Reports from '@/views/report/Reports.vue'
// 用户
import Users from '@/views/user/Users.vue'
Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        redirect: '/login',
    },
    {
        path: '/login',
        component: Login,
        name: 'Login',
    },
    {
        path: '/home',
        component: Home,
        name: 'home',
        redirect: '/home/welcome',
        children: [
            { path: 'welcome', component: Welcome, },
            { path: 'cate', component: Cate },
            { path: 'list', component: List },
            { path: 'order', component: Order },
            { path: 'rights', component: Rights },
            { path: 'roles', component: Roles },
            { path: 'reports', component: Reports },
            { path: 'users', component: Users },
        ]
    },


]



// 点击2次相同的路由报错-路由冗余
// 解决方法：
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(to) {
    return VueRouterPush.call(this, to).catch(err => err)
}

const router = new VueRouter({ routes, mode: "history", base: process.env.BASE_URL, })//hash默认值
export default router


// 例子：判断用户是否登陆，是否决定去Home页面
// let isLogin = true
router.beforeEach((to, from, next) => {
    // if (to.path === '/login' && isLogin) {
    //     // 去home页面,并且已经登陆
    //     next()
    // } else if (to.path === '/' || to.path === '/home') {
    //     // 首页放行
    //     next()
    // } else {
    //     // 返回登录页
    //     next('/home')
    // }
    // 1.如果访问是登陆页，直接放行
    // 2.从sessionStorage中取出token值
    // 3.如果token不存在，说明没有登陆，就强制跳转登陆页
    if (to.path === '/login') return next()
    let token = localStorage.getItem('token')
    if (!token) { return next('/login') }
    next()
})



